package cn.lsj.readwriteseparation.sharding;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @className: MyDBRangeShardingAlgorithm
 * @description: 范围分片算法
 * @author: https://www.cnblogs.com/chengxy-nds/p/13919981.html
 * @date: 2022/12/26
 **/
public class MyDBRangeShardingAlgorithm implements RangeShardingAlgorithm<Long> {

    @Override
    public Collection<String> doSharding(Collection<String> databaseNames, RangeShardingValue<Long> rangeShardingValue) {

        Set<String> result = new LinkedHashSet<>();
        // between and 的起始值
        long lower = rangeShardingValue.getValueRange().lowerEndpoint();
        Range<Long> valueRange = rangeShardingValue.getValueRange();
        long upper = 0;
        // 如果没有结束值，则默认查询所有的库
        if(valueRange.hasUpperBound()) {
            upper = valueRange.upperEndpoint();
        } else {
            return databaseNames;
        }
        // 循环范围计算分库逻辑
        for (long i = lower; i <= upper; i++) {
            for (String databaseName : databaseNames) {
                if (databaseName.endsWith(i % databaseNames.size() + "")) {
                    result.add(databaseName);
                }
            }
        }
        return result;
    }
}